package com.coda.service.impl;

import com.coda.adminVo.attr.AttrValueVo;
import com.coda.adminVo.graph.GraphVo;
import com.coda.adminVo.room.RoomDetailVo;
import com.coda.adminVo.room.RoomItemVo;
import com.coda.adminVo.room.RoomQueryVo;
import com.coda.adminVo.room.RoomSubmitVo;
import com.coda.constant.MessageConstant;
import com.coda.constant.StatusConstant;
import com.coda.entity.*;
import com.coda.exception.DeletionNotAllowedException;
import com.coda.mapper.ApartmentMapper;
import com.coda.mapper.LeaseMapper;
import com.coda.mapper.RoomMapper;
import com.coda.result.PageResult;
import com.coda.service.RoomService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoomServiceImpl implements RoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private ApartmentMapper apartmentMapper;
    @Autowired
    private LeaseMapper leaseMapper;
    @Autowired
    private TransactionTemplate transactionTemplate;

    /**
     * 根据条件分页查询房间列表
     *
     * @param current
     * @param size
     * @param roomQueryVo
     * @return
     */
    @Override
    public PageResult getPageList(Integer current, Integer size, RoomQueryVo roomQueryVo) {
        //设置分页参数
        PageHelper.startPage(current, size);
        //分页查询房间信息
        Page<RoomItemVo> page = roomMapper.getPageList(roomQueryVo);
        //查询公寓信息
        for (RoomItemVo roomItemVo : page) {
            ApartmentInfo apartmentInfo = apartmentMapper.getApartment(roomItemVo.getApartmentId());
            //判断房间入住状态
            LeaseAgreement leaseAgreement = leaseMapper.getStatus(roomItemVo.getApartmentId(), roomItemVo.getId());
            if (leaseAgreement != null && leaseAgreement.getStatus() == 2) {
                roomItemVo.setIsCheckIn(true);
                roomItemVo.setLeaseEndDate(leaseAgreement.getLeaseEndDate());
            } else {
                roomItemVo.setIsCheckIn(false);
            }
            roomItemVo.setApartmentInfo(apartmentInfo);
        }

        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    /**
     * 根据id删除房间信息
     *
     * @param id
     */
    @Override
    public void deleteRoomById(Long id) {
        RoomInfo roomInfo = roomMapper.getRoom(id);
        //删除房间信息，如果房间为发布状态则不能删除
        if (roomInfo.getIsRelease() == 1) {
            throw new DeletionNotAllowedException(MessageConstant.ROOM_IS_RELEASE);
        }

        transactionTemplate.execute(status -> {
            //删除房间信息
            roomMapper.delete(id);
            //删除对应的房间详细信息
            delete(id);
            return null;
        });

    }

    /**
     * 删除房间详细信息
     * @param id
     */
    private void delete(Long id){
        //删除对应的房间详细信息
        roomMapper.deleteRoomLeaseTerm(id);
        roomMapper.deleteRoomPaymentType(id);
        roomMapper.deleteRoomAttrValue(id);
        roomMapper.deleteRoomLabel(id);
        roomMapper.deleteRoomFacility(id);
        roomMapper.deleteGraph(id);
    }

    /**
     * 保存或更新房间信息
     *
     * @param roomSubmitVo
     */
    @Transactional
    @Override
    public void saveOrUpdate(RoomSubmitVo roomSubmitVo) {
        //判断id是否为空，id为空：insert，id不为空：update
        if (roomSubmitVo.getId() == null) {
            transactionTemplate.execute(status->{
                //插入房间信息
                RoomInfo roomInfo = new RoomInfo();
                BeanUtils.copyProperties(roomSubmitVo, roomInfo);
                roomInfo.setIsRelease(StatusConstant.DISABLE);
                roomMapper.insertRoom(roomInfo);

                //插入房间对应的关系
                setRoomDetail(roomSubmitVo, roomInfo);
                return null;
            });


        } else {
            transactionTemplate.execute(status -> {
                //更新房间信息
                RoomInfo roomInfo = new RoomInfo();
                BeanUtils.copyProperties(roomSubmitVo, roomInfo);
                roomMapper.updateRoom(roomInfo);

                //删除房间对应信息
                delete(roomInfo.getId());

                //插入房间对应的关系
                setRoomDetail(roomSubmitVo, roomInfo);
                return null;
            });

        }
    }

    /**
     * 根据id获取房间详细信息
     * @param id
     * @return
     */
    // todo 显示不了详细信息
    @Override
    public RoomDetailVo getRoomDetailVO(Long id) {
        //获取房间信息
        RoomInfo room = roomMapper.getRoom(id);
        //获取房间详细信息
        ApartmentInfo apartmentInfo = apartmentMapper.getApartment(room.getApartmentId());
        List<GraphVo> graphVoList = roomMapper.getGraph(id);
        List<AttrValueVo> attrValueList = roomMapper.getAttrValue(id);
        List<FacilityInfo> facilityInfoList = roomMapper.getFacility(id);
        List<LabelInfo> labelInfoList = roomMapper.getLabelInfo(id);
        List<PaymentType> paymentTypeList = roomMapper.getPaymentType(id);
        List<LeaseTerm> leaseTermList = roomMapper.getLeaseTermList(id);

        //赋值给vo对象
        RoomDetailVo roomDetailVo = new RoomDetailVo();
        BeanUtils.copyProperties(room,roomDetailVo);

        BeanUtils.copyProperties(room, roomDetailVo);
        roomDetailVo.setGraphVoList(graphVoList);
        roomDetailVo.setApartmentInfo(apartmentInfo);
        roomDetailVo.setGraphVoList(graphVoList);
        roomDetailVo.setAttrValueVoList(attrValueList);
        roomDetailVo.setFacilityInfoList(facilityInfoList);
        roomDetailVo.setLabelInfoList(labelInfoList);
        roomDetailVo.setPaymentTypeList(paymentTypeList);
        roomDetailVo.setLeaseTermList(leaseTermList);
        return roomDetailVo;
    }

    /**
     * 根据公寓id查询房间信息列表
     * @param id
     * @return
     */
    @Override
    public List<RoomInfo> getRoomList(Long id) {
        List<RoomInfo> roomInfoList = roomMapper.getRoomInfo(id);
        return roomInfoList;
    }

    /**
     * 根据id修改房间发布状态
     * @param id
     */
    @Override
    public void updateRelease(Long id,Integer status) {
        RoomInfo roomInfo = new RoomInfo();
        roomInfo.setId(id);
        roomInfo.setIsRelease(status);
        roomMapper.updateRoom(roomInfo);
    }

    /**
     * 此方法用于插入房间对应的信息
     */
    private void setRoomDetail(RoomSubmitVo roomSubmitVo, RoomInfo roomInfo) {
        //插入图片
        List<GraphInfo> graphInfoList = new ArrayList<>();
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        for (GraphVo graphVo : graphVoList) {
            GraphInfo graphInfo = GraphInfo.builder()
                    .name(graphVo.getName())
                    .itemType(StatusConstant.ROOM)
                    .itemId(roomInfo.getId())
                    .url(graphVo.getUrl()).build();
            graphInfoList.add(graphInfo);
        }
        apartmentMapper.insertGraphInfo(graphInfoList);

        //插入属性信息
        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        if (!(CollectionUtils.isEmpty(attrValueIds))) {
            List<RoomAttrValue> roomAttrValueList = new ArrayList<>();
            for (Long attrValueId : attrValueIds) {
                RoomAttrValue roomAttrValue = RoomAttrValue.builder()
                        .roomId(roomInfo.getId())
                        .attrValueId(attrValueId).build();
                roomAttrValueList.add(roomAttrValue);
            }
            roomMapper.insertAttrValue(roomAttrValueList);
        }

        //插入配套信息
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds();
        if (!(CollectionUtils.isEmpty(facilityInfoIds))) {
            List<RoomFacility> roomFacilities = new ArrayList<>();
            for (Long facilityInfoId : facilityInfoIds) {
                RoomFacility roomfacility = RoomFacility.builder()
                        .roomId(roomInfo.getId())
                        .facilityId(facilityInfoId).build();
                roomFacilities.add(roomfacility);
            }
            roomMapper.insertFacility(roomFacilities);
        }


        //插入标签信息
        List<Long> labelInfoIds = roomSubmitVo.getLabelInfoIds();
        if (!(CollectionUtils.isEmpty(labelInfoIds))) {
            List<RoomLabel> roomLabelList = new ArrayList<>();
            for (Long labelInfoId : labelInfoIds) {
                RoomLabel roomlabel = RoomLabel.builder()
                        .roomId(roomInfo.getId())
                        .labelId(labelInfoId).build();
                roomLabelList.add(roomlabel);
            }
            roomMapper.insertLabel(roomLabelList);
        }

        //插入支付方式信息
        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();
        if (!CollectionUtils.isEmpty(paymentTypeIds)) {
            List<RoomPaymentType> roomPaymentTypesList = new ArrayList<>();
            for (Long paymentTypeId : paymentTypeIds) {
                RoomPaymentType roomPaymentType = RoomPaymentType.builder()
                        .roomId(roomInfo.getId())
                        .paymentTypeId(paymentTypeId).build();
                roomPaymentTypesList.add(roomPaymentType);
            }
            roomMapper.insertPaymentType(roomPaymentTypesList);
        }

        //插入可选租期列表
        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if (!(CollectionUtils.isEmpty(leaseTermIds))) {
            List<RoomLeaseTerm> roomLeaseTerms = new ArrayList<>();
            for (Long leaseTermId : leaseTermIds) {
                RoomLeaseTerm roomLeaseTerm = RoomLeaseTerm.builder()
                        .roomId(roomInfo.getId())
                        .leaseTermId(leaseTermId).build();
                roomLeaseTerms.add(roomLeaseTerm);
            }
            roomMapper.insertLeaseTerm(roomLeaseTerms);
        }
    }


}
